package com.pagepub.core.tag.message;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pagepub.core.exception.ExceptionMessageParam;
import com.pagepub.core.exception.SysException;
import com.pagepub.core.utils.StringUtil;

/**
 * 消息盒处理器
 * 
 * @author ggd
 * 
 */
public class HtmlMessageProcess {
	private HttpServletRequest request;

	private HtmlMessageBox hmb = null;

	private Log log = LogFactory.getLog(HtmlMessageProcess.class);

	static String HTMLMESSAGEBOX_JSP_CHARSET = "UTF-8";

	public HtmlMessageProcess(HtmlMessageBox hmb, HttpServletRequest request) {
		this.hmb = hmb;
		this.request = request;
		if (hmb == null || request == null) {
			ExceptionMessageParam emp = new ExceptionMessageParam();
			emp.setKeyOrMessageText("HtmlMessageProcess()初始化错误!");
			log.error("HtmlMessageProcess()初始化错误!\n" + "hmb=" + hmb
					+ "\nrequest=" + request);
			throw new SysException(emp, null);
		}
		/**
		 * 初始化信息显示类型

		 */
		if (hmb.getMessageOnPageType() == HtmlMessageBox.MESSAGE_ON_PAGE_PREACTION_URL
				&& StringUtil.obj2Str(request.getHeader("Referer")).length() > 0) {
			hmb.setMessageOnPageURL(request.getHeader("Referer"));
		}
		if (hmb.getTargetName() == null) {
			hmb.setTargetName(HtmlMessageBox.TARGETTYPE_SELF);
		}

	}

	/**
	 * 处理显示信息
	 * 
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public HtmlMessageBox process() {
		String msg = StringUtil.replace(hmb.getMessage(), "\n", "<br>");
		msg = StringUtil.replace(msg, "\"", "\\\"");
		if (hmb.isUseResource()) {
			msg = StringUtil.getLocalResourceStr(msg, hmb.getResourceName());// Resources.getMessage(request,msg);//从资源文件取对应key的信息

		}
		if (hmb.getFormatParams() != null && hmb.getFormatParams().length > 0) {
			msg = MessageFormat.format(msg, hmb.getFormatParams());
		}

		hmb.setMessage(msg);

		if (hmb.isUseResource()) {
			for (int i = 0; i < hmb.getLinkMsg().length; i++) {
				String tmp = StringUtil.obj2Str(StringUtil.getLocalResourceStr(
						hmb.getLinkMsg()[i], hmb.getResourceName()));// (Resources.getMessage(request,
																		// hmb.getLinkMsg()[i]));
				if (tmp.length() > 0)// 资源文件有内容才赋值，否则用原来的
				{
					hmb.getLinkMsg()[i] = tmp;
				}
				tmp = null;
			}
			hmb.setLinkMsg(hmb.getLinkMsg());
		}
		if (hmb.getMessageOnPageType() == HtmlMessageBox.MESSAGE_ON_PAGE_PREACTION_URL
				|| hmb.getMessageOnPageType() == HtmlMessageBox.MESSAGE_ON_PAGE_SPECIFY_URL) {
			String content = "";
			String str = "";
			URL url =null;
			try {
				if (hmb.getMessageOnPageURL().indexOf("http") < 0) {//没有找到http
					String tmpUrl = request.getRequestURL().substring(
							0,
							request.getRequestURL().indexOf(
									request.getContextPath())
									+ request.getContextPath().length());
					tmpUrl += hmb.getMessageOnPageURL().indexOf("/") == 0 ? hmb
							.getMessageOnPageURL() : "/"
							+ hmb.getMessageOnPageURL();
					hmb.setMessageOnPageURL(tmpUrl);
					
				}
				if(hmb.getMessageOnPageURL().indexOf("http") > 0){
					url = new URL(hmb.getMessageOnPageURL());
					content=url.toString();	
				}	
						
				
//				content=url.getProtocol()+"://"+url.getAuthority()+url.getFile();
				
//				System.out.println("protocol="+ url.getProtocol());
//				System.out.println("host ="+ url.getHost());
//				System.out.println("filename="+ url.getFile());
//				System.out.println("port="+ url.getPort());
//				System.out.println("ref="+url.getRef());
//				System.out.println("query="+url.getQuery());
//				System.out.println("path="+url.getPath());
//				System.out.println("UserInfo="+url.getUserInfo());
//				System.out.println("Authority="+url.getAuthority());

//				BufferedReader isr = new BufferedReader(new InputStreamReader(
//						url.openStream(), HTMLMESSAGEBOX_JSP_CHARSET));
//				String str = "";
//				while ((str = isr.readLine()) != null) {
//					content += "\n" + str + "\n";// new
//													// String(str.getBytes(),"UTF-8")+"\n";
//				}
//				isr.close();
			} catch (MalformedURLException e) {
				log
						.error(
								"HtmlMessageBox.process()==>new URL(hmb.getMessageOnPageURL())错误!\nhmb.getMessageOnPageURL()=="
										+ hmb.getMessageOnPageURL(), e);
				ExceptionMessageParam emp = new ExceptionMessageParam();
				emp.setKeyOrMessageText("处理提示信息错误!");
				throw new SysException(emp, e);
			} catch (IOException e) {
				log
						.error(
								"HtmlMessageBox.process()==>new BufferedReader(new InputStreamReader(url.openStream()))错误!",
								e);
				ExceptionMessageParam emp = new ExceptionMessageParam();
				emp.setKeyOrMessageText("处理提示信息错误!");
				throw new SysException(emp, e);
			}
			request.setAttribute(HtmlMessageBox.MESSAGE_PAGES_CONTENT, content);
		}
		request.setAttribute(HtmlMessageBox.MESSAGE_PAGES_ATTRIBUTE_NAME, hmb);
		return hmb;
	}
}
